package com.itedge.infrastructure.web.controller.impl;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.itedge.infrastructure.domain.IEntity;
import com.itedge.infrastructure.service.domain.IEntityService;
import com.itedge.infrastructure.web.controller.IEntityController;

/**
 * Deafault implementation of {@link IEntityController}, abstracts logic for common used entity controller methods.
 * 
 * @author jhe
 *
 * @param <E>
 */
public abstract class AbstractEntityController<E extends IEntity> implements IEntityController {
	
	/** Entity service */
	protected IEntityService<E> entityService;
	
	/**
	 * Default constructor.
	 * 
	 * @param entityService
	 */
	protected AbstractEntityController(IEntityService<E> entityService) {
		this.entityService = entityService;
	}
	
	/**
	 * Implementing subclasses should return name of view used for list (table) view rendering.
	 * 
	 * @return name of view used for list rendering
	 */
	public abstract String getListView();
	
	/**
	 * Implementing subclasses should return name of model key for entities list.
	 * 
	 * @return model key for entities list
	 */
	public abstract String getModelKeyForEntitiesList();
	
	/**
	 * Implementing subclasses should return default page size for list view. 
	 * 
	 * @return default page size for list view
	 */
	public abstract int getDefaultPageSizeForListView();

	@Override
	@RequestMapping(method = RequestMethod.GET)
	public String list(@RequestParam(value = "page", required = false) Integer page, 
		@RequestParam(value = "size", required = false) Integer size, Model model) {
        if (page != null || size != null) {
            int sizeNo = size == null ? getDefaultPageSizeForListView() : size.intValue();
            model.addAttribute(getModelKeyForEntitiesList(), entityService.findEntityEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
            float nrOfPages = (float) entityService.countEntities() / sizeNo;
            model.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            model.addAttribute(getModelKeyForEntitiesList(), entityService.findAllEntities());
        }
		return getListView();
	}

}
